package com.zgh.zhongcan.filter;


import com.alibaba.fastjson.JSON;
import com.zgh.zhongcan.common.BaseContext;
import com.zgh.zhongcan.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查是否登录，否则跳转登录页面
 * @author 时侍
 * @version 1.0
 **/
    @WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符（springboot工具类）
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest= (HttpServletRequest) request;
        HttpServletResponse httpResponse= (HttpServletResponse) response;
        log.info("拦截到请求：{}",httpRequest.getRequestURI());

        //获取本次请求uri
        String requestURI = httpRequest.getRequestURI();
        //不需要处理的请求
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断是否需要处理
        boolean check = check(urls, requestURI);
        //不需要处理则放行
        if (check){
            log.info("本次请求{}不需要处理",requestURI);
            chain.doFilter(httpRequest,httpResponse);
            return;
        }

        //判断登录状态，若登录则放行
        if (httpRequest.getSession().getAttribute("employee") != null){
            log.info("用户已登录，id为{}",httpRequest.getSession().getAttribute("employee"));

            //获取当前登录用户的id
            Long empId = (Long) httpRequest.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);//给线程设置变量，将当前用户id保存在线程

            chain.doFilter(httpRequest,httpResponse);
            return;
        }

        //判断移动端用户登录状态，若登录则放行
        if (httpRequest.getSession().getAttribute("user") != null){
            log.info("用户已登录，id为{}",httpRequest.getSession().getAttribute("user"));

            //获取当前登录用户的id
            Long userId = (Long) httpRequest.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);//给线程设置变量，将当前用户id保存在线程

            chain.doFilter(httpRequest,httpResponse);
            return;
        }

        log.info("用户未登录");
        //若未登录，通过输出流的方式响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 匹配路径，判断是否放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);//路径匹配
            if (match){
                return true;
            }
        }
        return false;
    }
}
